package thread.processing;

import static java.lang.System.out;

public class ThreadStop implements Runnable {

	String word;
	int delay;
	volatile boolean started = false;
	volatile Thread This_Thread = null;

	public ThreadStop(String w, int d) {
		word = w;
		delay = d;
		out.println("Sleep time of " + word + " = " + delay);
	}

	public void start() {
		started = true;
		if (This_Thread == null) {
			This_Thread = new Thread(this);
			This_Thread.start();
		}
	}

	public void stop() {
		started = false;
		if (This_Thread != null) {
			This_Thread = null;
		}
	}

	public void run() {
		try {
			if (started) {									
				for (int count = 1; count < 10; count++) {
					out.printf("%s%d\t", word, count);
					Thread.sleep(delay);
				}
			}
		} catch (InterruptedException e) {
			out.println(e);
		}
	}

	public static void main(String[] args) {
		out.println("Ping Pong Thread demo");

		ThreadStop ping = new ThreadStop("Ping", 500);
		ping.start();
		ping.stop();
		new ThreadStop("Pong", 0).start();
	}

}

/*
 * Ping Pong Thread demo 3 Sleep time of Ping = 500 Sleep time of Pong = 0 Pong1
 * Pong2 Pong3 Pong4 Pong5 Pong6 Pong7 Pong8 Pong9
 */